/**
 * 树形工具类
 * 作者:郭海涛
 * 用法:
 * import {TreeUtil} from "@/utils/treeUtil"
 */
export class TreeUtil {
  static isLeaf(node) {
    return node.children && node.children.length ? false : true;
  }
  static filterNodes(nodes, filter, deep, parent) {
    if (deep == undefined) deep = 1;
    nodes = nodes.filter(node => {
      return filter(node, deep, parent);
    });
    nodes.forEach((node, index) => {
      if (node.children) {
        node.children = TreeUtil.filterNodes(
          node.children,
          filter,
          deep + 1,
          node,
        );
      }
    });
    return nodes;
  }

  static forEachNodes(nodes, callback, deep, parent) {
    if (deep == undefined) deep = 1;
    if (Array.isArray(nodes)) {
      nodes.forEach((node, index) => {
        callback(node, index, deep, parent);
        TreeUtil.forEachNodes(node.children, callback, deep + 1, node);
      });
    }
    return nodes;
  }
}
